/** 
* All Rights Reserved , Copyright (C) 2020 , 青岛鼎信通讯股份有限公司
* 
* FileManageService
* 文件记录
* 
* 修改纪录
* 2020-08-15 版本：1.0 donghang 创建。
* @version 版本：1.0
* @author 作者：donghang
* 创建日期：2020-08-15
*/
package com.topscomm.meet.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.topscomm.meet.MeetSystemConst;
import com.topscomm.meet.pojo.FileBlockRecordEntity;
import com.topscomm.meet.pojo.FileManageEntity;
import com.topscomm.meet.service.IFileManageService;
import com.topscomm.meet.service.impl.auto.FileManageServiceAuto;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringBufferProxy;

import cn.hutool.core.io.FileUtil;

@Service(value = "fileManageService")
@Scope(value = "singleton")
public class FileManageService extends FileManageServiceAuto implements IFileManageService {
	/**
	 * 文件块服务
	 */
	@Autowired
	FileBlockRecordService fileBlockRecordService;
	/**
	 * 音视频存储路径
	 */
	@Value("${file.audio.root.path}")
	private String uploadFolder;

	/**
	 * 上传文件块(控制同一个来源下的文件相同即可)
	 * 
	 * @description:
	 * @param fileBytes
	 * @param sourcetype
	 * @param sourceid
	 * @param blockEntity
	 * @return
	 * @author: donghang
	 * @date: 2020年8月22日下午5:57:34
	 * @modify:
	 */
	@Transactional(rollbackFor = Exception.class)
	public void uploadFileBlock(byte[] fileBytes, Map<String, Object> dataMap) {
		// 1.上传文件块
		fileBlockRecordService.uploadFileBlock(fileBytes, dataMap);
		StringBufferProxy sql = new StringBufferProxy();
		// 2.判断是否存在文件记录,新增文件记录
		sql.clear();
		sql.appendSingle(" identifier='{0}' and sourceid='{1}' and sourcetype='{2}'",
				ConvertUtil.convertToString(dataMap.get("identifier")),
				ConvertUtil.convertToLong(dataMap.get("sourceid")),
				ConvertUtil.convertToString(dataMap.get("sourcetype")));
		// 已经上传，则更新
		List<Map<String, Object>> fileMapList = this.queryMapByWhere(sql.toString());
		if (fileMapList.size() > 0) {
			sql.clear();
			sql.appendSingle(" 1=1 ");
			sql.appendSingle(" and identifier = '{0}' and sourceid='{1}' and sourcetype='{2}'",
					ConvertUtil.convertToString(dataMap.get("identifier")),
					ConvertUtil.convertToLong(dataMap.get("sourceid")),
					ConvertUtil.convertToString(dataMap.get("sourcetype")));
			Map<String, Object> updataMap = new HashMap<String, Object>();
			updataMap.put("name", ConvertUtil.convertToString(dataMap.get("filename")));
			updataMap.put("usercode", ConvertUtil.convertToString(dataMap.get("usercode")));
			updataMap.put("username", ConvertUtil.convertToString(dataMap.get("username")));
			updataMap.put("recordtime", new Date());
			this.updateByWhere(updataMap, sql.toString());
		}
		// 第一次上传新增记录
		if (fileMapList.size() == 0 && ConvertUtil.convertToInt(dataMap.get("blocknum")) == 1) {
			// 新增文件记录
			FileManageEntity fileManageEntity = new FileManageEntity();
			fileManageEntity.setIdentifier(ConvertUtil.convertToString(dataMap.get("identifier")));
			fileManageEntity.setFilemd5(ConvertUtil.convertToString(dataMap.get("filemd5")));
			fileManageEntity.setName(ConvertUtil.convertToString(dataMap.get("filename")));
			fileManageEntity.setSourceid(ConvertUtil.convertToLong(dataMap.get("sourceid")));
			fileManageEntity.setSourcetype(ConvertUtil.convertToString(dataMap.get("sourcetype")));
			fileManageEntity.setLocation(ConvertUtil.convertToString(dataMap.get("identifier")));
			fileManageEntity.setTotalblockcount(ConvertUtil.convertToInt(dataMap.get("totalblockcount")));
			fileManageEntity.setRecordtime(new Date());
			fileManageEntity.setUploadusercode(ConvertUtil.convertToString(dataMap.get("usercode")));
			fileManageEntity.setUploadusername(ConvertUtil.convertToString(dataMap.get("username")));
			fileManageEntity.setFilesize(ConvertUtil.convertToLong(dataMap.get("filesize")));
			fileManageEntity.setBlocksize(ConvertUtil.convertToLong(dataMap.get("blocksize")));
			fileManageEntity.setLocation(ConvertUtil.convertToString(dataMap.get("identifier")) + "-"
					+ ConvertUtil.convertToString(dataMap.get("sourceid"))
					+ ConvertUtil.convertToString(dataMap.get("sourcetype")) + "/splice/output.m3u8");
			fileManageEntity.setType(ConvertUtil.convertToString(dataMap.get("type")));
			fileManageEntity.setUploadstate(MeetSystemConst.FileUploadStateEnum.Uploading);
			fileManageEntity = this.insert(fileManageEntity);
		}

	}

	/**
	 * 检查上传的文件块号
	 * 
	 * @description:
	 * @param fileManageEntity
	 * @return
	 * @author: donghang
	 * @date: 2020年8月20日下午11:31:37
	 * @modify:
	 */
	public Map<String, Map<String, Object>> getUploadBlocks(Map<String, Object> paraMap) {
		// 查询文件所有已上传的块
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" 1=1 ");
		sql.appendSingle(" and identifier in ('{0}') and sourceid='{1}' and sourcetype='{2}' order by blocknum asc ",
				paraMap.get("qry_identifiers"), paraMap.get("qry_sourceid"), paraMap.get("qry_sourcetype"));
		List<FileBlockRecordEntity> fileBlockRecordEntityList = fileBlockRecordService.queryByWhere(sql.toString());

		// Map<String, List<Integer>> fileUploadBlocks = new HashMap<String,
		// List<Integer>>();
		Map<String, Map<String, Object>> fileUploadBlocks = new HashMap<String, Map<String, Object>>();
		fileBlockRecordEntityList.forEach(fileBlockRecordEntity -> {
			int blockNum = ConvertUtil.convertToInt(fileBlockRecordEntity.getBlocknum());
			String identifier = ConvertUtil.convertToString(fileBlockRecordEntity.getIdentifier());
			if (fileUploadBlocks.containsKey(identifier)) {
				Map<String, Object> uploadBlockMap = fileUploadBlocks.get(identifier);
				List<Integer> alreadyUploadBlockList = (List<Integer>) uploadBlockMap.get("uploadblocklist");
				if (!alreadyUploadBlockList.contains(blockNum))
					alreadyUploadBlockList.add(blockNum);
			} else {
				Map<String, Object> uploadBlockMap = new HashMap<String, Object>();
				List<Integer> alreadyUploadBlockList = new ArrayList<Integer>();
				alreadyUploadBlockList.add(blockNum);
				uploadBlockMap.put("blocksize", fileBlockRecordEntity.getBlocksize());
				uploadBlockMap.put("uploadblocklist", alreadyUploadBlockList);
				fileUploadBlocks.put(identifier, uploadBlockMap);
			}
		});
		return fileUploadBlocks;
	}

	/**
	 * 删除记录和块记录
	 * 
	 * @description:
	 * @param paraMap
	 * @author: donghang
	 * @date: 2020年9月16日下午6:45:48
	 * @modify:
	 */
	@Override
	public void deleteFile(Map<String, Object> paraMap) {
		String[] ids = ConvertUtil.convertToString(paraMap.get("ids")).split(",");
		// 删除块记录
		for (String id : ids) {
			FileManageEntity fileManageEntity = this.queryById(id);
			StringBufferProxy sql = new StringBufferProxy();
			// 1.块记录删除
			sql.clear();
			sql.appendSingle(" identifier='{0}' and sourceid='{1}' and sourcetype='{2}'",
					fileManageEntity.getIdentifier(), fileManageEntity.getSourceid(), fileManageEntity.getSourcetype());
			this.fileBlockRecordService.deleteByWhere(sql.toString());
			// 2.文件遍历删除
			String path = fileManageEntity.getIdentifier() + "-" + fileManageEntity.getSourceid()
					+ fileManageEntity.getSourcetype();
			FileUtil.del(uploadFolder + "/" + path);
			// 3.文件记录删除
			this.deleteById(id);
		}

	}
}
